<?php

namespace common\services\myhtsq;

use common\entities\ContractEntity;
use common\entities\myhtsq\ContractPropertyEntity;
use common\error\ErrorCode;
use common\error\ErrorMsg;
use common\repositories\myhtsq\ContractEmailContactsRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\InvoiceReceivableRepository;
use common\services\BaseService;
use common\entities\ConfigEntity;
use common\repositories\myhtsq\ContractPaymentRepository;
use common\repositories\myhtsq\InvoicePaymentRepository;
use common\services\common\EmailService;
use common\services\common\MyscrmContractSyncDeleteDataService;
use common\services\myhtsq\InvoiceService;
use common\models\myhtsq\PaymentAchievementModel;
use common\repositories\myhtsq\PaymentAchievementRepository;
use common\repositories\myhtsq\ContractReceivableRepository;
use common\repositories\myhtsq\SignAchievementRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\SignDelyRepository;
use common\entities\myhtsq\SignDelyEntity;
use common\support\StringHelper;
use common\services\myhtsq\ErpInterfaceService;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use common\entities\myhtsq\MyscrmContractDistributionAmountEntity;
use common\models\myhtsq\ContractApiLogModel;
use common\repositories\myhtsq\ContractApiLogRepository;
use common\error\ErrorInfo;

/**
 * Description of ContractPaymentService
 * 合同回款服务
 * @author chenxc
 */
class ContractPaymentService extends BaseService {

    public function __construct($config = array()) {
        parent::__construct($config);
    }

    /**
     * 根据合同ID获取对应的回款信息
     * @param string $contractId 合同ID
     * @return array
     */
    public function getPaymentInfoByContractId($contractId) {
        $paymentInfos = ContractPaymentRepository::getPaymentInfoByContractId($contractId);

        if (isset($paymentInfos) && count($paymentInfos) > 0) {
            foreach ($paymentInfos as $k => $v) {
                $invoicePayments = InvoicePaymentRepository::getInoicePaymentByPaymentId($v['payment_id']);
                if (!(isset($invoicePayments) && count($invoicePayments) > 0)) {
                    continue;
                }

                $billing_invoice_no = [];
                foreach ($invoicePayments as $v1) {
                    if (!in_array($v1['invoice_no'], $billing_invoice_no)) {
                        $billing_invoice_no[] = $v1['invoice_no'];
                    }
                }

                $paymentInfos[$k]['billing_invoice_no'] = implode(';', $billing_invoice_no);
            }
        }

        return $paymentInfos;
    }

    /**
     * 回款绑定发票
     * @param \common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return bool
     */
    public function bindContractPaymentToInvoice($contractPaymentModel)
    {
        if ($contractPaymentModel->validate()) {
            $configDataBase = ContractEntity::getDb();
            $trans = $configDataBase->beginTransaction();
            try{
                $doRelationResult = $this->__doInvoicePaymentRelation($contractPaymentModel->payment_id, $contractPaymentModel);
                if($doRelationResult === false){
                    $trans->rollBack();
                    $this->setAndReturn(__LINE__, '处理回款跟发票关系时失败');
                }

                $trans->commit();
                return true;
            }catch(Exception $e){
                \Yii::error((string)$e);
                $trans->rollBack();
                return $this->setAndReturn(__LINE__, $e);
            }
        }else {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_VERIFY_FAIL);
        }
    }

    /**
     * 处理回款跟发票的关系
     * @param $payment_id
     * @param \common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return bool
     */
    private function __doInvoicePaymentRelation($payment_id, $contractPaymentModel)
    {
        $refundArray = [];
        //付款责任人跟售前人员的对应(用于发送邮件:云售前人员人员也可以收到邮件)
        $refundUniteSalesIds = [];
        $invoicePayments = $contractPaymentModel->invoicePayments;
        if (isset($invoicePayments) && count($invoicePayments) > 0) {

            foreach ($invoicePayments as $v) {
                if (floatval($v['cur_payment_amount']) == 0) {
                    continue;
                }

                $v['payment_id'] = $payment_id;
                $res = InvoicePaymentRepository::addInvoicePayment($v);
                if ($res === false) {
                    return self::setAndReturn(InvoicePaymentRepository::getErrCode());
                }

                // 重新刷新发票的payment_amount
                $res = $this->summaryInvoicePaymentAmount($v['invoice_id']);
                if ($res === false) {
                    return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL);
                }

                // 重新刷新应收款的received_amount
                $res = $this->summaryContractReceivableReceivedAmount($v['receivable_id']);
                if ($res === false) {
                    return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL);
                }

                //获取收款责任人
                $invoiceReceivableInfo = InvoiceReceivableRepository::getInvoiceReceivableByPK($v['invoice_receivable_id']);
                if (!empty($invoiceReceivableInfo)) {
                    $contractReceivableInfo = ContractReceivableRepository::getContractReceivableById($invoiceReceivableInfo['receivable_id']);
                    if (!empty($contractReceivableInfo)) {
                        $payeeId = $contractReceivableInfo['payee_id'];
                        if (array_key_exists($payeeId, $refundArray)) {
                            $refundArray[$payeeId] += floatval($v['cur_payment_amount']);
                        } else {
                            $refundArray[$payeeId] = floatval($v['cur_payment_amount']);
                        }
                        $refundUniteSalesIds[$payeeId] = $contractReceivableInfo['unite_sales_id'];
                    }
                }
            }

            $tmp_receivable_item_id = $tmp_money_category_item_id = '';
            $contractReceivable = ContractReceivableRepository::getContractReceivableById($invoicePayments[0]['receivable_id']);
            if (isset($contractReceivable)) {
                $tmp_receivable_item_id = $contractReceivable['receivable_item_id'];
                $tmp_money_category_item_id = $contractReceivable['money_category_item_id'];
            }

            // 新增一笔回款业绩
            $paymentAchievementModel = new PaymentAchievementModel(['scenario' => 'add']);
            $paymentAchievementModel->contract_id = $contractPaymentModel->contract_id;
            $paymentAchievementModel->receivable_item_id = $tmp_receivable_item_id;
            $paymentAchievementModel->money_category_item_id = $tmp_money_category_item_id;
            $paymentAchievementModel->achievement_amount = $contractPaymentModel->payment_amount;
            $paymentAchievementModel->invoice_payment_id = "";
            $paymentAchievementModel->payment_id = $payment_id;

            //回款业绩实收时间 = 回款到帐时间
            $paymentAchievementModel->received_time = $contractPaymentModel->payment_date;
            //回款业绩归属时间 默认= 业绩实收时间
            $paymentAchievementModel->achievement_belong_time = $contractPaymentModel->payment_date;

            //业绩归属
            $signAchievements = SignAchievementRepository::getSignAchievementListByContractId($contractPaymentModel->contract_id);
            $contractMng = ContractManageRepository::getContractManageModelByContractId($contractPaymentModel->contract_id);

            if (!empty($signAchievements)) { //有签约业绩,业绩归属信息以此为准
                $paymentAchievementModel->belong_by = $signAchievements[0]['belong_by'];
                $paymentAchievementModel->department_by = $signAchievements[0]['department_by'];
                $paymentAchievementModel->area_by = $signAchievements[0]['area_by'];
                $paymentAchievementModel->abu_by = $signAchievements[0]['abu_by'];
                $paymentAchievementModel->erp_achievement_belong = $signAchievements[0]['erp_achievement_belong'];
                $paymentAchievementModel->erp_achievement_belong_abu = $signAchievements[0]['erp_achievement_belong_abu'];
                $paymentAchievementModel->erp_achievement_belong_abu_owner = $signAchievements[0]['erp_achievement_belong_abu_owner'];
                $paymentAchievementModel->erp_achievement_belong_bu_manager = $signAchievements[0]['erp_achievement_belong_bu_manager'];
                $paymentAchievementModel->manager_by = $signAchievements[0]['manager_by'];
                $paymentAchievementModel->erp_achievement_belong_bu = $signAchievements[0]['erp_achievement_belong_bu'];

            } elseif (isset($contractMng)) {
                $paymentAchievementModel->belong_by = $contractMng['sign_people_id'];
                $paymentAchievementModel->area_by = $contractMng['area_id'];
                $paymentAchievementModel->fillBuInfoByUser();
            }

            $res = $this->addPaymentAchievement($paymentAchievementModel);
            if ($res === false) {
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_SAVE_FAIL);
            }
        }

        //新增一笔交付业绩
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractPaymentModel->contract_id); //获取model
        $signDelyArr = SignDelyRepository::getSignDelyListByContractId($contractPaymentModel->contract_id);
        $signDelyInfo = isset($signDelyArr[0]) ? $signDelyArr[0] : [];
        $signDelyEntity = new SignDelyEntity();
        $signDelyEntity->dely_id = StringHelper::uuid();
        $signDelyEntity->payment_id = $payment_id;
        $signDelyEntity->contract_id = $contractPaymentModel->contract_id;
        $signDelyEntity->dely_on = $contractPaymentModel->payment_date;
        $signDelyEntity->dely_amount = $contractPaymentModel->payment_amount;
        $signDelyEntity->attribute_name = $contractModel->attribute_name;
        $signDelyEntity->created_on = date('Y-m-d H:i:s');
        if (!empty($signDelyInfo)) {
            $signDelyEntity->attribute_name = $signDelyInfo['attribute_name'];
            $signDelyEntity->belong_by = $signDelyInfo['belong_by'];
            $signDelyEntity->department_by = $signDelyInfo['department_by'];
            $signDelyEntity->area_by = $signDelyInfo['area_by'];
            $signDelyEntity->dely_belong_on = $signDelyInfo['dely_belong_on'];
        }
        SignDelyRepository::addSignDely($signDelyEntity);

        // TODO 正式环境 且 合同性质不为明源直属的合同 才发邮件
        if(!YII_ENV_PROD || $contractModel->contract_property_id == ContractPropertyEntity::MY_PROPERTY_DIRECTLY_OPERATION_ID){
            return true;
        }

        try {

            //获取累计回款金额
            $totalRefundAmount = InvoicePaymentRepository::getTotalPaymentAmountByContractId($contractPaymentModel->contract_id);
            //获取合同信息
            $contractInfo = ContractManageRepository::getContractManageModelByContractId($contractPaymentModel->contract_id);
            foreach ($refundArray as $key => $item) {
                $emailParams = [
                    'contractId' => $contractInfo->contract_code,
                    'custFullName' => $contractModel->customer_full_name,
                    'custName' => $contractInfo->customer_name,
                    'contractAmount' => $contractInfo->sign_amount,
                    'signDate' => $contractInfo->sign_date,
                    'registerDate' => $contractPaymentModel->register_date,
                    'paymentAccountName' => $contractPaymentModel->payment_account_name,
                    'receiver' => '',
                    'receivedAmount' => number_format($item, 2) .
                        '(回款' . number_format($contractPaymentModel->payment_amount, 2) .
                        ',绑定发票' . number_format($item, 2) . ')',
                    'totalReceivedAmount' => $totalRefundAmount
                ];
                $uniteSalesId = isset($refundUniteSalesIds[$key]) ? $refundUniteSalesIds[$key] : "";
                $cc = [];
                if (!empty($uniteSalesId)) {
                    $user = ErpUserRepository::getUserById($uniteSalesId);
                    if (!empty($user) && !empty($user["Email"])) {
                        $cc = array_merge($cc, [$user["Email"] => $user["UserName"]]);
                    }
                }
                $this->sendEmail($key, '【合同管理】回款信息', 'revenue', $emailParams, $cc);
            }
        } catch (\Exception $ex) {
            \Yii::error("回款发送邮件失败");
        }
        return true;
    }

    /**
     * 保存合同回款
     * @param \common\models\myhtsq\ContractPaymentModel $contractPaymentModel
     * @return bool|string   失败|回款Guid
     */
    public function saveContractPayment($contractPaymentModel,$contractId) {

        if ($contractPaymentModel->validate()) {
            // 开启事务
            $configDataBase = ContractEntity::getDb();
            $trans = $configDataBase->beginTransaction();

            try {
                if (isset($contractPaymentModel->payment_id) && !empty($contractPaymentModel->payment_id)) {
                    //修改
                    $result = ContractPaymentRepository::updateContractPayment($contractPaymentModel);
                    $payment_id = $contractPaymentModel->payment_id;
                } else {
                    //新增
                    $result = ContractPaymentRepository::addContractPayment($contractPaymentModel);
                    $payment_id = $result;
                }

                if ($result === false) {
                    // 回滚事务
                    $trans->rollBack();
                    return self::setAndReturn(ContractPaymentRepository::getErrCode());
                }

                //通知ERP回款信息被修改
                if(isset($contractPaymentModel->DhkGUID) && $contractPaymentModel->DhkGUID) {//引入未开票回款时没有这个字段的，不用通知ERP
                    /** @var ErpInterfaceService $erpInterfaceService */
                    $erpInterfaceService = \Yii::createObject(ErpInterfaceService::className());
                    $updateAccountHkResult = $erpInterfaceService->updateAccountHk($contractPaymentModel->DhkGUID, $contractPaymentModel->payment_amount);
                    if ($updateAccountHkResult === false) {
                        $trans->rollBack();

                        $contractApiLogModel = new contractApiLogModel();
                        $contractApiLogModel->log_type = 2;
                        $contractApiLogModel->call_line = __LINE__;
                        $contractApiLogModel->call_method = __METHOD__;
                        $contractApiLogModel->call_parametes = json_encode($contractPaymentModel,JSON_UNESCAPED_UNICODE);
                        $contractApiLogModel->return_data = json_encode($updateAccountHkResult,JSON_UNESCAPED_UNICODE);
                        $contractApiLogModel->return_code = ErrorInfo::getErrCode();
                        $contractApiLogModel->error_msg = ErrorInfo::getErrMsg();
                        $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';
                        ContractApiLogRepository::addContractApiLogRecord($contractApiLogModel);

                        return self::setAndReturn(__LINE__, '通知ERP回款信息被修改失败！');
                    }
                }

                $contractApiLogModel = new contractApiLogModel();
                $contractApiLogModel->log_type = 2;
                $contractApiLogModel->call_line = __LINE__;
                $contractApiLogModel->call_method = __METHOD__;
                $contractApiLogModel->call_parametes = json_encode($contractPaymentModel,JSON_UNESCAPED_UNICODE);
                $contractApiLogModel->return_data = json_encode(array(),JSON_UNESCAPED_UNICODE);
                $contractApiLogModel->return_code = ErrorInfo::getErrCode();
                $contractApiLogModel->error_msg = ErrorInfo::getErrMsg();
                $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';

                if(!isset($contractPaymentModel->DhkGUID)){
                    $contractApiLogModel->maintain_remark = 'DhkGUID 为空, 引入未开票回款不通知erp';
                }

                ContractApiLogRepository::addContractApiLogRecord($contractApiLogModel);

                //发票回款信息
                $doRelationResult = $this->__doInvoicePaymentRelation($payment_id, $contractPaymentModel);
                if ($doRelationResult === false) {
                    $trans->rollBack();

                    $contractApiLogModel = new contractApiLogModel();
                    $contractApiLogModel->log_type = 1;
                    $contractApiLogModel->call_line = __LINE__;
                    $contractApiLogModel->call_method = __METHOD__;
                    $contractApiLogModel->call_parametes = json_encode($contractPaymentModel,JSON_UNESCAPED_UNICODE);
                    $contractApiLogModel->return_data = json_encode($doRelationResult,JSON_UNESCAPED_UNICODE);
                    $contractApiLogModel->return_code = ErrorInfo::getErrCode();
                    $contractApiLogModel->error_msg = ErrorInfo::getErrMsg();
                    $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';
                    ContractApiLogRepository::addContractApiLogRecord($contractApiLogModel);
                    return self::setAndReturn(__LINE__, '处理发票回款信息失败！');
                }

                $trans->commit();
                return $result;
            }catch(Exception $e){
                $trans->rollBack();
                \Yii::error("保存回款失败：". (string)$e);
                $contractApiLogModel = new contractApiLogModel();
                $contractApiLogModel->log_type = 1;
                $contractApiLogModel->call_line = __LINE__;
                $contractApiLogModel->call_method = __METHOD__;
                $contractApiLogModel->call_parametes = json_encode($contractPaymentModel,JSON_UNESCAPED_UNICODE);
                $contractApiLogModel->return_data = json_encode([],JSON_UNESCAPED_UNICODE);
                $contractApiLogModel->return_code = ErrorInfo::getErrCode();
                $contractApiLogModel->error_msg = ErrorInfo::getErrMsg();
                $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';
                ContractApiLogRepository::addContractApiLogRecord($contractApiLogModel);
                return self::setAndReturn(__LINE__, '保存回款失败！');
            }
        } else {
                $contractApiLogModel = new contractApiLogModel();
                $contractApiLogModel->log_type = 1;
                $contractApiLogModel->call_line = __LINE__;
                $contractApiLogModel->call_method = __METHOD__;
                $contractApiLogModel->call_parametes = json_encode($contractPaymentModel,JSON_UNESCAPED_UNICODE);
                $contractApiLogModel->return_data = json_encode(array(),JSON_UNESCAPED_UNICODE);
                $contractApiLogModel->return_code = ErrorCode::ERR_CONTRACT_PAYMENT_FORM_VERIFY_FAIL;
                $contractApiLogModel->error_msg = '合同回款保存校验失败';
                $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';
                ContractApiLogRepository::addContractApiLogRecord($contractApiLogModel);
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_FORM_VERIFY_FAIL);
        }
    }

    private function sendEmail($userId, $subject, $template, $params, $cc)
    {
        $user = ErpUserRepository::getUserById($userId);
        if (empty($user)) {
            return;
        }
        //获取抄送人
        $copyToEMail = ContractEmailContactsRepository::getCCContactsByBu($user['BUGUID'], $user['UserCode']);

        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];
        $params['userName'] = $user['UserName'];

        if (is_array($cc)) {
            $copyToEMail = array_merge($copyToEMail,$cc);
        }
        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];
        return EmailService::sendEMail([$user['Email']=>$user['UserName']], $subject, 'contract/' .$template, $params, $copyToEMail);
    }

    /**
     * 重新刷新发票的回款金额
     * @param string $invoiceId 发票ID
     * @return boolean true刷新成功/false刷新失败
     */
    private function summaryInvoicePaymentAmount($invoiceId) {
        return InvoiceService::summaryInvoicePaymentAmount($invoiceId);
    }

    /**
     * 重新刷新应收款的已收金额(received_amount)
     * @param string $receivableId 应收款ID
     * @return boolean true刷新成功/false刷新失败
     */
    public function summaryContractReceivableReceivedAmount($receivableId) {
        return ContractReceivableService::summaryContractReceivableReceivedAmount($receivableId);
    }

    /**
     * 解除回款与发票的关联关系
     * @param $paymentIds
     * @return bool
     */
    public function unBindPaymentForInvoice($paymentIds)
    {
        if (empty($paymentIds)) {
            return self::setAndReturn(__LINE__, '请选择要取消绑定的回款');
        }

        // 开启事务
        $configDataBase = ContractEntity::getDb();
        $trans = $configDataBase->beginTransaction();

        try {
            foreach ($paymentIds as $paymentId) {
                $paymentEntity = ContractPaymentRepository::getPaymentEntityByPaymentId($paymentId);
                if (!isset($paymentEntity)) {
                    return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_NOT_EXISTS, '合同回款不存在');
                }

                $otherBusinessResult = $this->deletePaymentForInvoice($paymentId, $paymentEntity, false);
                if ($otherBusinessResult === false) {
                    $trans->rollBack();
                    return self::setAndReturn(__LINE__, self::getErrMsg());
                }
            }

            $trans->commit();
        } catch (\Exception $e) {
            $trans->rollBack();
            return self::setAndReturn(__LINE__, '解除回款与发票的关联关系失败' . $e->getMessage());
        }
        /** @var MyscrmContractSyncDeleteDataService $myscrmContractSyncDeleteDataService */
        $myscrmContractSyncDeleteDataService = \Yii::createObject(MyscrmContractSyncDeleteDataService::className());
        $myscrmContractSyncDeleteDataService->addData('myscrm_contract_payment', 'payment_id', $paymentEntity->payment_id);

        return true;
    }

    private function deletePaymentForInvoice($paymentId, $paymentEntity, $isDeletePerformance = true)
    {
        // 获取对应的 回款与发票及应收款对应关系
        $invoiceIds = $receivableIds = [];
        $invoicePayments = InvoicePaymentRepository::getInoicePaymentByPaymentId($paymentId);
        if (isset($invoicePayments) && count($invoicePayments) > 0) {
            foreach ($invoicePayments as $k => $v) {
                if (isset($v['invoice_id']) && !empty($v['invoice_id']) && !in_array($v['invoice_id'], $invoiceIds)) {
                    $invoiceIds[] = $v['invoice_id'];
                }

                if (isset($v['receivable_id']) && !empty($v['receivable_id']) && !in_array($v['receivable_id'], $receivableIds)) {
                    $receivableIds[] = $v['receivable_id'];
                }

                // 删除 回款与发票及应收款对应关系
                $result = InvoicePaymentRepository::deleteInvoicePaymentByInvoicePaymentId($v['invoice_payment_id']);
                if ($result === false) {
                    return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_DELETE_FAIL);
                }
            }
        }

        if($isDeletePerformance === true) {
            // 删除对应的回款业绩
            $result = PaymentAchievementRepository::deletePaymentAchievementByPaymentId($paymentId);
            if ($result === false) {
                return self::setAndReturn(__LINE__, '删除对应的回款业绩失败');
            }

            // 删除交付业绩
            $result = SignDelyRepository::deleteSignDelyByPaymentId($paymentId);
            if ($result === false) {
                return self::setAndReturn(__LINE__, '删除交付业绩失败');
            }
        }

        // 重新刷新发票的payment_amount
        foreach ($invoiceIds as $k => $v) {
            $result = $this->summaryInvoicePaymentAmount($v);
            if ($result === false) {
                return self::setAndReturn(__LINE__, '重新刷新发票的payment_amount失败');
            }
        }

        // 重新刷新应收款的received_amount
        foreach ($receivableIds as $k => $v) {

            $result = $this->summaryContractReceivableReceivedAmount($v);
            if ($result === false) {
                return self::setAndReturn(__LINE__, '重新刷新应收款的received_amount失败');
            }
        }

        //通知ERP回款信息被修改
        if(isset($paymentEntity->finance_code) && $paymentEntity->finance_code) {
            /** @var ErpInterfaceService $erpInterfaceService */
            $erpInterfaceService = \Yii::createObject(ErpInterfaceService::className());

            $amount = $paymentEntity->payment_amount;

            $updateAccountHkResult = $erpInterfaceService->updateAccountHkForCode($paymentEntity->finance_code, -$amount);//删除传负数

            if ($updateAccountHkResult === false) {
                return self::setAndReturn(__LINE__, '通知ERP回款信息被修改失败！');
            }
        }

        return true;
    }

    /**
     * 删除回款信息
     * @param string $paymentId 回款ID
     * @return boolean true删除成功/false删除失败
     */
    public function deleteContractPayment($paymentId,$delpayment=null) {

        $paymentEntity = ContractPaymentRepository::getPaymentEntityByPaymentId($paymentId);

        if (!isset($paymentEntity)) {
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_NOT_EXISTS);
        }

        // 开启事务
        $configDataBase = ContractEntity::getDb();
        $trans = $configDataBase->beginTransaction();

        try {

            $result = $paymentEntity->delete();
            if ($result === false) {
                $trans->rollBack();
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_DELETE_FAIL);
            }

            $otherBusinessResult = $this->deletePaymentForInvoice($paymentId, $paymentEntity);
            if ($otherBusinessResult === false) {
                $trans->rollBack();
                return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_DELETE_FAIL);
            }

            //维护回款分摊金额
            /** @var ContractService $contractService */
            $contractService = \Yii::createObject(ContractService::className());
            $docalculatePaymentResult = $contractService->calculatePayment($paymentEntity->contract_id);
            if ($docalculatePaymentResult === false) {
                $trans->rollBack();
                return self::setAndReturn(__LINE__, '维护回款分摊金额失败！');
            }

            $trans->commit();
        }catch (\Exception $e){
            $trans->rollBack();
            return self::setAndReturn(ErrorCode::ERR_CONTRACT_PAYMENT_DELETE_FAIL, $e->getMessage());
        }

        //TODO 记录删除回款模式
        ContractPaymentRepository::delPaymentMode($paymentId,$delpayment);

        return true;
    }

    /**
     * 获取单条回款信息
     * @param $paymentId
     * @return \common\entities\myhtsq\ContractPaymentEntity|null
     */
    public function getContractPayment($paymentId)
    {
        return ContractPaymentRepository::getContractPaymentEntity($paymentId);
    }

    /**
     * 根据合同id获取还没有完全关联发票的回款
     * @param string $contractId 合同id
     * @return array
     */
    public function getContractPaymentHaveAmountByContract($contractId) {
        return ContractPaymentRepository::getContractPaymentHaveAmountByContract($contractId);
    }

    /**
     * 新增回款业绩
     * @param \common\models\myhtsq\PaymentAchievementModel $paymentAchievementModel 回款业绩模型
     * @return boolean|string 成功时返回业绩id，false表示失败
     */
    private function addPaymentAchievement($paymentAchievementModel) {
        return PaymentAchievementRepository::addPaymentAchievement($paymentAchievementModel);
    }

    /**
     *  根据财务编号获取对应的合同回款信息
     * @param string $financeCode
     * @return array
     */
    public function getContractPaymentInfoByFinanceCode($financeCode) {
        return ContractPaymentRepository::getContractPaymentInfoByFinanceCode($financeCode);
    }

    /**
     * 根据发票ID获取已关联的回款列表
     * @param $invoiceId
     * @return array|boolean
     */
    public function getContractPaymentInfoByInvoiceId($invoiceId)
    {
        if(empty($invoiceId)){
            return self::setAndReturn(__LINE__, '发票ID不能为空');
        }

        return InvoicePaymentRepository::getInvoicePaymentInfoByInvoiceId($invoiceId);
    }
}
